<template>
    <el-dialog title="Warning" width="50%" center>
      
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="id" prop="id" v-model="showEl" v-if="showEl==true">
          <el-input/>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="菜单code" prop="code">
          <el-input v-model="ruleForm.code" />
        </el-form-item>
        <el-form-item label="菜单层级" prop="leval">
          <el-select v-model="ruleForm.leval" placeholder="选择菜单层级" @change="levalChange">
            <el-option key="1" label="一级" :value="1" />
            <el-option key="2" label="二级" :value="2" />
          </el-select>
        </el-form-item>
      
        <el-form-item v-if="ruleForm.leval==2" label="父级菜单Id" prop="parentId">
          <!-- <el-input v-model.number="ruleForm.parentId"/> -->
          <el-select v-model="ruleForm.parentId" placeholder="父级菜单" :disabled="parentDisable">
            <el-option
              v-for="item in pMenu"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="ruleForm.leval==2 && ruleForm.parentId!=undefined" label="菜单path" prop="path">
          <el-input v-model="ruleForm.path" />
          <el-upload
            ref="upload"
            class="upload-demo"
            action="/api/upload/cache"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :on-success="onSuccess"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <el-button class="ml-3" type="success" @click="submitUpload">
              上传
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef);">提交</el-button>
        <el-button @click="resetForm(ruleFormRef);">
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed,ref,reactive,nextTick,toRefs,Ref } from "vue";
import axios from '@/request';
import { ruleForm } from "@/type/LearnMenu";
import { ElTable, FormInstance, FormRules,ElMessage,genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import api from '@/api/index'


// const centerDialogVisible = ref(true)
const value = ref('')
const parentDisable = ref(false)

const props = defineProps({  // 可以拿到它的值
  dataListPath: String,
  recordId: Number,
})
//此处必须用toRefs，否则将失去响应式
const { dataListPath, recordId} = toRefs(props);

// form表单相关
const showEl = ref(false)

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<ruleForm>({
  id: undefined,
  name: '',
  code: '',
  path: '',
  leval: undefined,
  parentId: undefined,
})

// 判断recordId是否为空，为空新增，不为空编辑
const getRecord = () => {
  if(recordId?.value != undefined){
    const parms = axios.get<ruleForm>(api.learn+"/"+recordId?.value);
    parms.then((res)=>{
      // console.log(res.data);
      ruleForm.id = res.data?.id
      ruleForm.name = res.data?.name? res.data?.name:''
      ruleForm.code = res.data?.code? res.data?.code:''
      ruleForm.path = res.data?.path? res.data?.path:''
      ruleForm.leval = res.data?.leval
      ruleForm.parentId = res.data?.parentId
    });
  }
}
getRecord();

const rules = reactive<FormRules<ruleForm>>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 1, max: 20, message: 'Length should be 1 to 20', trigger: 'blur' },
  ],
  code: [
    { required: true, message: 'Please input Activity code', trigger: 'blur' },
    { min: 1, max: 20, message: 'Length should be 1 to 20', trigger: 'blur' },
  ],
  path: [
    { required: true, message: 'Please input Activity path', trigger: 'blur' },
    { min: 1, max: 255, message: 'Length should be 1 to 100', trigger: 'blur' },
  ],
  leval: [
    {
      required: true,
      message: 'Please select Activity leval',
      trigger: 'change',
    },
  ],
  parentId: [
    {
      required: true,
      message: 'Please select Activity parent',
      trigger: 'change',
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const parms = axios.post(dataListPath?.value as string,ruleForm)
      parms.then((res)=>{
        if(res.msg == "success"){
          ElMessage({
            message: '提交成功.',
            type: 'success',
          })
          resetForm(formEl)
          refresh();
        }else {
          ElMessage.error('提交失败.')
        }
      });
    } else {
      console.log('error submit!', fields)
      ElMessage.error('校验失败.')
    }
  })
}
// 关闭当前弹框
const emit = defineEmits(["changeMsg","refreshTable"]);
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields();
  emit('changeMsg');
}
// 刷新父组件中的list数据
function refresh(){
  emit('refreshTable');
}
const pMenu: Ref<ruleForm[]> = ref([])

const params = {
  leval: 1
}
const levalChange = (value:any)=>{
// 判断如果选择1级,父菜单自动赋值0
  if(value == 1) {
    ruleForm.parentId = 0
    parentDisable.value = true
  }else {
    parentDisable.value = false
    // 查询level为0的一级菜单
    const parms = axios.get<ruleForm[]>(api.learnQuery,params);
    parms.then((res)=>{
      pMenu.value = res.data? res.data:[];
      // console.log(pMenu);
    });
  };
}

// 上传文件
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
  // 将文件上传到临时文件夹
  // console.log(upload)
}

const onSuccess = (res: any) => {
  console.log(res.data)
  // 获取父菜单code
  var path = "/md"
  pMenu.value.forEach((menu) => {
    if(menu.id === ruleForm.parentId){
      path = path + "/" + menu.code
    }
  });
  ruleForm.path = path + "/" + res.data
}
</script>